package h3

import (
	"bytes"
	"github.com/lucas-clemente/quic-go/quicvarint"
)

// Datagram
// HTTP/3 Datagram {
//	   Quarter Stream ID (i),
//	   [Context ID (i)],
//	   HTTP Datagram Payload (..),
// }
type Datagram struct {
	StreamId uint64
	Payload  string
}

func ParseDatagram(raw []byte) *Datagram {
	reader := bytes.NewReader(raw)
	streamId, _ := quicvarint.Read(reader)
	messageBuf := bytes.Buffer{}
	_, _ = reader.WriteTo(&messageBuf)
	return &Datagram{
		StreamId: streamId,
		Payload:  string(messageBuf.Bytes()),
	}
}

func (f *Datagram) ToBytes() []byte {
	buf := bytes.Buffer{}
	// StreamId
	quicvarint.Write(&buf, f.StreamId)
	buf.Write([]byte(f.Payload))
	return buf.Bytes()
}
